package com.resou.reader.bookshelf.readhistory;

import android.text.TextUtils;

import com.resou.reader.ReSouApplication;
import com.resou.reader.base.ResouBasePresenter;
import com.resou.reader.data.bookshelf.model.ReadRecord;
import com.resou.reader.data.local.LitePalHelper;
import com.resou.reader.data.readhistory.ReadHistoryRepository;
import com.resou.reader.bookshelf.readhistory.datasupport.ReaderHistory;
import com.resou.reader.utils.AppExecutors;
import com.resou.reader.utils.NetworkUtils;
import com.resou.reader.utils.ToastUtil;
import com.resou.reader.utils.eventbus.LoadBookEvent;

import org.greenrobot.eventbus.EventBus;
import org.litepal.LitePal;

import java.util.List;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by ${Garrett} on 2018/9/16.
 * Contact me krouky@outlook.com
 */
public class ReadHistoryPresenter extends ResouBasePresenter<IReadHistoryView> {

    public static final int PAGE_SIZE = 15;
    private final ReadHistoryRepository mReadHistoryRepository;

    public ReadHistoryPresenter(IReadHistoryView view) {
        super(view);
        mReadHistoryRepository = ReadHistoryRepository.getInstance();
    }

    private int mCurrentPage = 0;

    /**
     * 加载服务端记录
     */
    public void loadRemoteRecord(String token, int page) {
        if (TextUtils.isEmpty(token)) {
            return;
        }
        mCurrentPage = 0;
        addCompositeDisposable(
                mReadHistoryRepository.loadRemoteRecord(token, page, PAGE_SIZE)
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(result -> {
                            if (result.getCode() == 0) {
                                ReadRecord record = result.getData();
                                List<ReadRecord.ReadRecordBean> readRecord = record.getReadRecord();
                                if (readRecord.size() < PAGE_SIZE) {
                                    if (page == 0) {
                                        mView.getSmartRefreshLayout().finishRefresh();
                                    }
                                    mView.setRemoteRecord(readRecord);
                                    mView.getSmartRefreshLayout().finishLoadMoreWithNoMoreData();
                                } else {
                                    if (page == 0) {
                                        mView.getSmartRefreshLayout().finishRefresh();
                                    }
                                    mView.setRemoteRecord(readRecord);
                                    mView.getSmartRefreshLayout().finishLoadMore();
                                }
                                saveRemoteRecord(readRecord);
//                                mView.setRemoteRecord(record.getReadRecord());
//                                mCurrentPage = mCurrentPage + 1;
                            }
                            mView.finishRefresh();
                        }, throwable -> {
                            mView.showError(new Throwable("网络异常"));
                            mView.finishRefresh();
                        })
        );
    }

//    public void loadNextRemoteRecord(String token) {
//        addCompositeDisposable(
//                mReadHistoryRepository.loadRemoteRecord(token, mCurrentPage, PAGE_SIZE)
//                        .subscribeOn(Schedulers.io())
//                        .observeOn(AndroidSchedulers.mainThread())
//                        .subscribe(result -> {
//                            if (result.getCode() == 0) {
//                                ReadRecord record = result.getData();
//                                List<ReadRecord.ReadRecordBean> readRecord = record.getReadRecord();
//                                mView.addRemoteRecord(record.getReadRecord());
//                                saveRemoteRecord(readRecord);
//                                mCurrentPage = mCurrentPage + 1;
//                            }
//                        }, throwable -> {
//                            mView.showError(throwable);
//                        }, () -> {
//
//                        })
//        );
//    }

    private void saveRemoteRecord(List<ReadRecord.ReadRecordBean> records) {
        AppExecutors.getAppExecutors().diskIO().execute(() -> {
            LitePalHelper.saveReadRecord(records);
        });
    }

    public void queryReadHistory() {
        addCompositeDisposable(
                Observable.create((ObservableOnSubscribe<List<ReaderHistory>>) emitter -> {
//                            .select("bookId", "name", "author", "picUrl", "historyChapterId"
//                            , "chapterIndex", "charIndex", "userUpdateTime", "historyChapterName", "chapterSum")
//                            .where("userUpdateTime > ?", "0")
                    List<ReaderHistory> list = LitePalHelper.loadReadHistory();
                    emitter.onNext(list);
                })
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(histories -> {
                                    if (histories != null && histories.size() > 0) {
                                        mView.setReadHistory(histories);
                                        mView.finishRefresh();
                                    } else {
                                        mView.setReadHistory(null);
                                    }
                                },
                                throwable -> {
                                    mView.showError(new Throwable("网络异常"));
                                    mView.finishRefresh();
                                })
        );
    }

    public void clearRemoteHistory(String token) {
        addCompositeDisposable(
                mReadHistoryRepository.clearReadRecord(token)
                        .subscribeOn(getIOSchedulers())
                        .observeOn(getIOSchedulers())
                        .subscribe(result -> {
                            if (result.getCode() == 0) {
                                LitePalHelper.logicallyDeleteReadHistory();
                                EventBus.getDefault().post(new LoadBookEvent());
                                loadRemoteRecord(token, 0);
                            } else {
                                ToastUtil.makeDebugLongToast(result.getMsg());
                            }
                        }, throwable -> {
                            ToastUtil.makeDebugLongToast(throwable.getMessage());
                            mView.showError(throwable);
                        })
        );

    }

    public void clearLocalHistory() {
        LitePalHelper.logicallyDeleteReadHistory();
        queryReadHistory();
    }
}
